package hydrap2p.servicemanager.listen;

import hydrap2p.ServiceLocation;
import hydrap2p.servicemanager.ServiceController;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class Listeners{

	private static List<Listener> listeners = new LinkedList<Listener>();
	public static ServiceController controller = null;
	
	public static void addListener(Listener listener)
	{
		synchronized(listeners)
		{
			if (!listeners.contains(listener))
			{
				ListenerQueue temp=new ListenerQueue(listener);
				listeners.add(temp);
				syncListener(temp);
			}
			
		}
		System.out.println("Added listener "+listener);
	}
	public static void delListener(Listener listener)
	{
		synchronized(listeners)
		{
			listeners.remove(listener);
		}
		listener.stop();
	}
	
	private static void syncListener(Listener listener)
	{
		for (Map.Entry<String, ServiceLocation> entry : controller.getAllServiceLocations().entrySet())
		{
			try {
				listener.newService(entry.getKey(), entry.getValue());
			} catch (Exception e) {
				// Invalid listener
				delListener(listener);
				break;
			}
		}
	}

	public static void newService(String name, ServiceLocation location) {
		synchronized(listeners)
		{
			for (Listener listener : listeners)
			{
				try {
					listener.newService(name, location);
				} catch (Exception e) {
					delListener(listener);
				}
			}
		}
	}

	public static void delService(String name) {
		synchronized(listeners)
		{
			for (Listener listener : listeners)
			{
				try {
					listener.delService(name);
				} catch (Exception e) {
					delListener(listener);
				}
			}
		}
	}

}
